﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using GTAuto.DAL.DAL;
using GTAuto.DAL.Entities;
using GTAuto.Site.BackEnd.ApCode.Filters;

namespace GTAuto.Site.BackEnd.Controllers
{
    [FirmSection]
    public class FirmsController : Controller
    {
        //
        // GET: /Firms/

        public ActionResult Index()
        {
            int count;
            List<GTFirmCategory> cats = DALFirmCategory.Singleton.GetPaged(1, 10000, out count); 
            return View(cats);
        }


        public ActionResult FirmCategoryEdit(int? id)
        {
            
            GTFirmCategory category = null;
            category = id == null ? new GTFirmCategory() : DALFirmCategory.Singleton.Get((int)id);

            return View(category);
        }


        [HttpPost]
        public ActionResult FirmCategoryEdit(GTFirmCategory gtBrand, HttpPostedFileBase Logo)
        {
            List<string> Error = new List<string>();
            if (Logo != null)
            {

                string filename = Guid.NewGuid().ToString() + "." + Logo.FileName.Split('.')[1];

                string filePath = Path.Combine(HttpContext.Server.MapPath(Url.Content(@"/Uploads/BrendLogos/"))
               , Path.GetFileName(filename));

                Logo.SaveAs(filePath);
                gtBrand.Logo = filename;
            }

         
            if (string.IsNullOrEmpty(gtBrand.Name))
                Error.Add("Название не может быть пустым");


            if (Error.Count == 0)
            {
                if (gtBrand.Id > 0)
                {
                    GTFirmCategory oldBrand = DALFirmCategory.Singleton.Get(gtBrand.Id);

                    if (string.IsNullOrEmpty(gtBrand.Logo))
                        gtBrand.Logo = oldBrand.Logo;
                    DALFirmCategory.Singleton.Update(gtBrand);
                }
                else
                {
                    gtBrand = DALFirmCategory.Singleton.Add(gtBrand);
                }
               return RedirectToAction("Index");
            }
            else
            {
                gtBrand.Logo = "";
            }

            ViewBag.Errs = Error;


            return View(gtBrand);
        }


        public ActionResult Delete(int id)
        {
            DALFirmCategory.Singleton.Delete(id);
            return RedirectToAction("Index");
        }


        public ActionResult DeleteFirm(int id)
        {
            DALFirms.Singleton.Delete(id);
            return RedirectToAction("FirmsAll");
        }

        public ActionResult FirmsAll()
        {
            int count;
            List<GTFirm> firms = DALFirms.Singleton.GetPaged(1, 10000, out count);
            return View(firms);
        }


        public ActionResult FirmEdit(int? id)
        {
            Session["FirmId"] = id;
            GTFirm firm = null;
            firm = id == null ? new GTFirm() : DALFirms.Singleton.Get((int)id);
            return View(firm);
        }


        [HttpPost, ValidateInput(false)]
        public ActionResult FirmEdit(GTFirm gtBrand, HttpPostedFileBase Logo,FormCollection collection)
        {
            List<string> Error = new List<string>();
            if (Logo != null)
            {

                string filename = Guid.NewGuid().ToString() + "." + Logo.FileName.Split('.')[1];

                string filePath = Path.Combine(HttpContext.Server.MapPath(Url.Content(@"/Uploads/BrendLogos/"))
               , Path.GetFileName(filename));

                Logo.SaveAs(filePath);
                gtBrand.Logo = filename;
            }


            if (string.IsNullOrEmpty(gtBrand.Name))
                Error.Add("Название не может быть пустым");


            if (string.IsNullOrEmpty(gtBrand.ShortName))
                gtBrand.ShortName = gtBrand.Name;

            if (Error.Count == 0)
            {
                if (gtBrand.Id > 0)
                {
                    GTFirm oldBrand = DALFirms.Singleton.Get(gtBrand.Id);

                    if (string.IsNullOrEmpty(gtBrand.Logo))
                        gtBrand.Logo = oldBrand.Logo;
                    DALFirms.Singleton.Update(gtBrand);
                }
                else
                {
                    gtBrand = DALFirms.Singleton.Add(gtBrand);
                }


                int count;
                var cats = DALFirmCategory.Singleton.GetPaged(1, 1000, out count);

                foreach (var gtFirmCategory in cats)
                { 
                    if(collection["Category_"+gtFirmCategory.Id]=="false")
                    {
                        DALFirms.Singleton.DeleteInCategory(gtBrand.Id,gtFirmCategory.Id);
                    }
                    else
                    {
                        DALFirms.Singleton.AddToCategory(gtBrand.Id, gtFirmCategory.Id);
                    }
                }

               // 
                Session["FirmId"] = gtBrand.Id;
                ViewBag.Succes = "Успешно сохранено";
                return View(gtBrand);
            }
            else
            {
                gtBrand.Logo = "";
            }

            ViewBag.Errs = Error;


            return View(gtBrand);
        }



        public ActionResult AdressEdit(int? id)
        {
            GTFirmAdress firm = null;
            firm = id == null ? new GTFirmAdress() : DALFirmAdress.Singleton.Get((int)id);
            firm.FirmId = (int)Session["FirmId"];
            return View(firm);
        }


        [HttpPost, ValidateInput(false)]
        public ActionResult AdressEdit(GTFirmAdress gtBrand, FormCollection collection)
        {
            List<string> Error = new List<string>();

            if (Error.Count == 0)
            {
                if (gtBrand.Id > 0)
                {
                    DALFirmAdress.Singleton.Update(gtBrand);
                }
                else
                {
                    gtBrand = DALFirmAdress.Singleton.Add(gtBrand);
                }

                return RedirectToAction("FirmEdit", new {@id = gtBrand.FirmId});
            }
          
            ViewBag.Errs = Error;
            return View(gtBrand);
        }


        public  ActionResult DeleteAdreses(int id)
        { 
            string firmId;
            GTFirmAdress gtFirmAdress = DALFirmAdress.Singleton.Get(id);
            DALFirmAdress.Singleton.Delete(id);
            return RedirectToAction("FirmEdit", new { @id = gtFirmAdress.FirmId });
        }


    }
}
